using System;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Globalization;
using AjaxControlToolkit;
using System.Collections;

[assembly: System.Web.UI.WebResource("AjaxControlToolkitEx.ScrollableGridViewExtenderBehavior.js", "text/javascript")]
[assembly: System.Web.UI.WebResource("AjaxControlToolkitEx.ScrollableGridViewExtenderBehavior.css", "text/css")]

namespace AjaxControlToolkitEx
{
    public enum AutoSizeType
    {
        None = 0,
        Extend = 1,
        Grow = 2
    }

    [RequiredScript(typeof(CommonToolkitScripts))]
    [Designer(typeof(ScrollableGridViewExtenderDesigner))]
    //[ClientScriptResource("AjaxControlToolkitEx.ScrollableGridViewExtenderBehavior", "AjaxControlToolkitEx.ScrollableGridViewExtenderBehavior.js")]
    //[ClientCssResource("AjaxControlToolkitEx.ScrollableGridViewExtenderBehavior.css")]

    [ClientScriptResource("AjaxControlToolkitEx.ScrollableGridViewExtenderBehavior", "AjaxControlToolkitEx.ScrollableGridViewExtenderBehavior")]    
    [ClientCssResource("AjaxControlToolkitEx.ScrollableGridViewExtenderBehavior")]
    [TargetControlType(typeof(Control))]
    public class ScrollableGridViewExtender : ExtenderControlBaseEx
    {
        // TODO: Add your property accessors here.
        //

        [ExtenderControlProperty]
        [DefaultValue("")]
        [IDReferenceProperty(typeof(Panel))]
        [RequiredProperty]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1706:ShortAcronymsShouldBeUppercase", Justification = "Following ASP.NET AJAX pattern")]
        public string ContainerPanelID
        {
            get { return GetPropertyValue("ContainerPanelID", ""); }
            set { SetPropertyValue("ContainerPanelID", value); }
        }


        [DefaultValue(true)]
        [ExtenderControlProperty]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1706:ShortAcronymsShouldBeUppercase", Justification = "Following ASP.NET AJAX pattern")]
        public bool FreezeHeader
        {
            get { return GetPropertyValue("FreezeHeader", true); }
            set { SetPropertyValue("FreezeHeader", value); }
        }


        [DefaultValue(true)]
        [ExtenderControlProperty]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1706:ShortAcronymsShouldBeUppercase", Justification = "Following ASP.NET AJAX pattern")]
        public bool FreezeFooter
        {
            get { return GetPropertyValue("FreezeFooter", true); }
            set { SetPropertyValue("FreezeFooter", value); }
        }


        [DefaultValue("")]
        [ExtenderControlProperty]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1706:ShortAcronymsShouldBeUppercase", Justification = "Following ASP.NET AJAX pattern")]
        public string FreezeColumnsIndex
        {
            get { return GetPropertyValue("FreezeColumnsIndex", ""); }
            set { SetPropertyValue("FreezeColumnsIndex", value); }
        }

        [DefaultValue("")]
        [ExtenderControlProperty]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1706:ShortAcronymsShouldBeUppercase", Justification = "Following ASP.NET AJAX pattern")]
        public string FreezeHeaderStyleCssClass
        {
            get { return GetPropertyValue("FreezeHeaderStyleCssClass", ""); }
            set { SetPropertyValue("FreezeHeaderStyleCssClass", value); }
        }

        [DefaultValue("")]
        [ExtenderControlProperty]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1706:ShortAcronymsShouldBeUppercase", Justification = "Following ASP.NET AJAX pattern")]
        public string FreezeColumnStyleCssClass
        {
            get { return GetPropertyValue("FreezeColumnStyleCssClass", ""); }
            set { SetPropertyValue("FreezeColumnStyleCssClass", value); }
        }


        [DefaultValue("")]
        [ExtenderControlProperty]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1706:ShortAcronymsShouldBeUppercase", Justification = "Following ASP.NET AJAX pattern")]
        public string FreezeColumnHeaderStyleCssClass
        {
            get { return GetPropertyValue("FreezeColumnHeaderStyleCssClass", ""); }
            set { SetPropertyValue("FreezeColumnHeaderStyleCssClass", value); }
        }

        [DefaultValue(false)]
        [ExtenderControlProperty]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1706:ShortAcronymsShouldBeUppercase", Justification = "Following ASP.NET AJAX pattern")]
        public bool DisableOnPostBack
        {
            get { return GetPropertyValue("DisableOnPostBack", false); }
            set { SetPropertyValue("DisableOnPostBack", value); }
        }

        [ExtenderControlProperty()]
        [DefaultValue(AutoSizeType.None)]
        public AutoSizeType HorizontalAutoSize
        {
            get { return GetPropertyValue("HorizontalAutoSize", AutoSizeType.None); }
            set { SetPropertyValue("HorizontalAutoSize", value); }
        }

        [ExtenderControlProperty()]
        [DefaultValue(AutoSizeType.None)]
        public AutoSizeType VerticalAutoSize
        {
            get { return GetPropertyValue("VerticalAutoSize", AutoSizeType.None); }
            set { SetPropertyValue("VerticalAutoSize", value); }
        }

        [DefaultValue(0)]
        [ExtenderControlProperty]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1706:ShortAcronymsShouldBeUppercase", Justification = "Following ASP.NET AJAX pattern")]
        public int AutoSizeWidthOffset
        {
            get { return GetPropertyValue("AutoSizeWidthOffset", 0); }
            set { SetPropertyValue("AutoSizeWidthOffset", value); }
        }
        [DefaultValue(0)]
        [ExtenderControlProperty]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1706:ShortAcronymsShouldBeUppercase", Justification = "Following ASP.NET AJAX pattern")]
        public int AutoSizeHeightOffset
        {
            get { return GetPropertyValue("AutoSizeHeightOffset", 0); }
            set { SetPropertyValue("AutoSizeHeightOffset", value); }
        }

        [DefaultValue("")]
        [ExtenderControlProperty]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1706:ShortAcronymsShouldBeUppercase", Justification = "Following ASP.NET AJAX pattern")]
        public string HiddenFieldID
        {
            get { return GetPropertyValue("HiddenFieldID", ""); }
            set { SetPropertyValue("HiddenFieldID", value); }
        }

        protected string HFID
        {
            get { return ID + "hf"; }
        }

        protected override void OnInit(EventArgs e)
        {
            CreateClientHiddenField();
            Page.PreLoad += new EventHandler(Page_PreLoad);
            if (!(TargetControl is GridView))
                throw new Exception("TargetControl of the ScrollableGridViewExtender must be type of GridView");

            GridView gv = TargetControl as GridView;

            gv.DataBound += new EventHandler(gv_DataBound);
            base.OnInit(e);
        }

        void gv_DataBound(object sender, EventArgs e)
        {
            this.FreezeCells();
            this.FreezeColumns();
        }

        private void FreezeCells()
        {
            GridView gv = TargetControl as GridView;

            if (this.FreezeHeader)
            {
                if (gv.HeaderRow != null)
                    foreach (DataControlFieldHeaderCell th in gv.HeaderRow.Cells)
                    {
                        th.CssClass = "FixTop" + " " + FreezeHeaderStyleCssClass;
                        //th.Style[HtmlTextWriterStyle.Top] = "expression(this.offsetParent.scrollTop)";
                        //th.Style[HtmlTextWriterStyle.Position] = "relative";
                        //th.Style[HtmlTextWriterStyle.ZIndex] = "expression(this.offsetParent.style.zIndex + 2)";
                    }
            }
            if (this.FreezeFooter)
            {
                if (gv.FooterRow != null)
                    foreach (TableCell cell in gv.FooterRow.Cells)
                    {
                        cell.CssClass = "FixBottom" + " " + FreezeHeaderStyleCssClass;
                        //cell.Style[HtmlTextWriterStyle.Left] = "expression(this.offsetParent.scrollLeft)";
                        //cell.Style[HtmlTextWriterStyle.Position] = "relative";
                        //cell.Style[HtmlTextWriterStyle.ZIndex] = "expression(this.offsetParent.style.zIndex + 1)";
                    }
            }
        }
        private void FreezeColumns()
        {
            GridView gv = TargetControl as GridView;

            if (!string.IsNullOrEmpty(this.FreezeColumnsIndex))
            {
                ArrayList cols = new ArrayList(this.FreezeColumnsIndex.Split(','));

                for (int i = 0; i < gv.HeaderRow.Cells.Count; i++)
                {
                    if (cols.Contains(i.ToString()))
                    {
                        gv.HeaderRow.Cells[i].CssClass = "FixTopLeft" + " " + FreezeColumnHeaderStyleCssClass;

                        //gv.HeaderRow.Cells[i].Style[HtmlTextWriterStyle.Top] = "expression(this.offsetParent.scrollTop)";
                        //gv.HeaderRow.Cells[i].Style[HtmlTextWriterStyle.Left] = "expression(this.offsetParent.scrollLeft)";
                        //gv.HeaderRow.Cells[i].Style[HtmlTextWriterStyle.Position] = "relative";
                        //gv.HeaderRow.Cells[i].Style[HtmlTextWriterStyle.ZIndex] = "expression(this.offsetParent.style.zIndex + 3)";
                    }
                }
                foreach (GridViewRow row in gv.Rows)
                {
                    for (int i = 0; i < row.Cells.Count; i++)
                    {
                        if (cols.Contains(i.ToString()))
                        {
                            row.Cells[i].CssClass = "FixLeft" + " " + FreezeColumnStyleCssClass;
                            //row.Cells[i].Style[HtmlTextWriterStyle.Left] = "expression(this.offsetParent.scrollLeft)";
                            //row.Cells[i].Style[HtmlTextWriterStyle.Position] = "relative";
                            //row.Cells[i].Style[HtmlTextWriterStyle.ZIndex] = "expression(this.offsetParent.style.zIndex + 1)";
                        }
                    }
                }
            }
        }

        void Page_PreLoad(object sender, EventArgs e)
        {
            LoadClientHiddenFieldValue();
        }
        private HiddenField CreateClientHiddenField()
        {
            //HiddenField ctl = (HiddenField)NamingContainer.FindControl(HFID);
            //if (ctl != null)
            //return ctl;
            HiddenField field = new HiddenField();
            field.ID = HFID;
            Controls.Add(field);
            HiddenFieldID = GetClientID(HFID);

            return field;
        }
        private string Value = "1";
        private void LoadClientHiddenFieldValue()
        {
            HiddenField hiddenField = (HiddenField)NamingContainer.FindControl(HFID);

            if ((hiddenField != null) && !string.IsNullOrEmpty(hiddenField.Value))
            {
                Value = hiddenField.Value;
            }
        }
        protected void SaveClientClientHiddenFieldValue()
        {
            HiddenField hiddenField = (HiddenField)NamingContainer.FindControl(HFID);

            if (hiddenField != null)
            {
                hiddenField.Value = Value;
            }
        }
        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            this.BehaviorID = GetClientID(ID) + "_behaviour";
        }
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            SaveClientClientHiddenFieldValue();

            /*
            if (_operation != null)
            {
                string operation = _operation;
                {
                    string script = string.Format(CultureInfo.InvariantCulture, @"
                    (function() {{
                        var fn = function() {{
                            window.setTimeout('var behavior = $find(\'{0}\');if (behavior) {{behavior._resizeHandler(null);}}', 200);
                            Sys.Application.remove_load(fn);
                        }};
                        Sys.Application.add_load(fn);
                    }})();", BehaviorID);
                    ScriptManager.RegisterStartupScript(this, typeof(ScrollableGridViewExtender), operation + BehaviorID, Helper.Trim(script), true);
                }
            }
            */
        }

        /*
        private string _operation = null;
        public void AdjustSize()
        {
            string operation = "adjustsize";
            _operation = operation;
        }
        */
    }
}
